//
//  HDUtil.m
//  DooiooOnline
//
//  Created by koki on 14-11-6.
//  Copyright (c) 2014年 dooioo. All rights reserved.
//

#define KShowMessageDefaultWidth   210.0f

#import "HDUtil.h"
#import <CommonCrypto/CommonHMAC.h>
#import <sys/types.h>
#import <sys/sysctl.h>
#import "Globals.h"

@implementation HDUtil

//检查电话号码是否合法
+(BOOL)checkPhoneNumInput:(NSString *)number
{
    NSString * MOBILE = @"^[0-9]{8,20}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    BOOL res1 = [regextestmobile evaluateWithObject:number];
    
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+(BOOL)checkMoblieNumber:(NSString *)mobileNumber
{
//    NSString * MOBILE = @"^1[3|4|5|8][0-9]\\d{8}$";
//    NSString * MOBILE = @"^\\d{11}$";
//    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
//    BOOL res1 = [regextestmobile evaluateWithObject:number];
//    if (res1)
//    {
//        return YES;
//    }
//    else
//    {
//        return NO;
//    }
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,152,157,158,159,178,182,183,184,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|47|5[0-235-9]|78|8[02435-9])\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,152,155,156,185,186
     */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,1349,153,180,181,189
     */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349|700)\\d{7}$";
    /**
     * 大陆地区固话及小灵通
     * 区号：010,020,021,022,023,024,025,027,028,029
     * 号码：七位或八位
     */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    //兼容以上 新手机号段 13,14,15,17,18...
    NSString * NEW = @"^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    NSPredicate *regextestnew = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", NEW];

    if (([regextestmobile evaluateWithObject:mobileNumber] == YES)
        || ([regextestcm evaluateWithObject:mobileNumber] == YES)
        || ([regextestct evaluateWithObject:mobileNumber] == YES)
        || ([regextestcu evaluateWithObject:mobileNumber] == YES)
        || ([regextestnew evaluateWithObject:mobileNumber] == YES))
    {
        if([regextestcm evaluateWithObject:mobileNumber] == YES) {
            NSLog(@"China Mobile");
        } else if([regextestct evaluateWithObject:mobileNumber] == YES) {
            NSLog(@"China Telecom");
        } else if ([regextestcu evaluateWithObject:mobileNumber] == YES) {
            NSLog(@"China Unicom");
        } else if ([regextestnew evaluateWithObject:mobileNumber] == YES) {
            NSLog(@"New Mobile");
        } else {
            NSLog(@"Unknown");
        }
        return YES;
    } else {
        return NO;
    }
}

+(BOOL)checkEmail:(NSString *)email
{
    NSString * EMAIL = @"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}@[a-zA-Z0-9][a-zA-Z0-9\\-]{0,6}+(\\.[a-zA-Z][a-zA-Z\\-]{0,6})+";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", EMAIL];
    BOOL res1 = [regextestmobile evaluateWithObject:email];
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//身份证号
+ (BOOL) validateIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

//检查名字是否合法
+(BOOL)checkNameInput:(NSString *)number
{
    NSString * name = @"^([\u4E00-\u9FA5]+|[a-zA-Z]+)$";
    NSPredicate *regextestaccount = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", name];
    BOOL res1 = [regextestaccount evaluateWithObject:number];
    if (res1)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//检查密码是否合法必须为数字字母组合
+(BOOL)checkPasswordInput:(NSString *)password
{
    NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:password];
    return isMatch;
}

#pragma mark 判断密码的正则表达式仅支持字母数字
+(BOOL)validatePassword:(NSString *)passWord
{
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,16}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}

//获取字符串的size
+(CGSize)getSizeWithText:(NSString*)text fontSize:(int)fontSize
{
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"STHeitiSC-Light" size:fontSize]}];
    return size;
}

//获取字符串的size
+(CGSize)getSizeWithText:(NSString*)text font:(UIFont*)font
{
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: font}];
    return size;
}

+(CGSize)getSizeWithText:(NSString*)text boldfontSize:(int)fontSize
{
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont boldSystemFontOfSize:fontSize]}];
    return size;
}

//创建指定字窜的Label
+(UILabel*)UILabelWithText:(NSString*)text fontSize:(int)fontSize
{
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"STHeitiSC-Light" size:fontSize]}];
    UILabel* Label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    Label.text=text;
    Label.backgroundColor=[UIColor clearColor];
    Label.font=[UIFont fontWithName:@"STHeitiSC-Light" size:fontSize];
    return Label;
}

//创建指定字窜的Label
+(UILabel*)UILabelWithText:(NSString*)text boldFontSize:(int)fontSize
{
    CGSize size=[text sizeWithAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"STHeitiSC-Light" size:fontSize]}];
    UILabel* Label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, size.width, size.height)];
    Label.text=text;
    Label.backgroundColor=[UIColor clearColor];
    Label.font=[UIFont boldSystemFontOfSize:fontSize];
    return Label;
}

+(void)shakeAnimationOfView:(UIView*)view
{
    CGFloat rotation = 0.5;
    CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@"transform"];
    shake.duration = 0.13;
    shake.autoreverses = YES;
    shake.repeatCount  = 2;
    shake.removedOnCompletion = YES;
    shake.fromValue = [NSValue valueWithCATransform3D:CATransform3DRotate(view.layer.transform,-rotation, 0.0 ,0.0 ,1.0)];
    shake.toValue   = [NSValue valueWithCATransform3D:CATransform3DRotate(view.layer.transform, rotation, 0.0 ,0.0 ,1.0)];
    [view.layer addAnimation:shake forKey:@"shakeAnimation"];
}

+(UIImage*)getSnapshotFromView:(UIView*)view
{
    UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 1);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
    UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshot;
}

+(UIImage*)getSnapshotFromView:(UIView*)view rect:(CGRect)rect
{
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 1);
    [view drawViewHierarchyInRect:rect afterScreenUpdates:NO];
    UIImage *snapshot = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return snapshot;
}

+(void)addShoppingAnimation:(UIImageView*)imageView PointArray:(NSArray*)pointAarray delegate:(id)delegate
{
    UIBezierPath *path = [UIBezierPath bezierPath];
    NSValue* valueTemp=pointAarray[0];
    CGPoint startPoint = [valueTemp CGPointValue];
    [path moveToPoint:startPoint];
    
    valueTemp=pointAarray[1];
    CGPoint centerPoint = [valueTemp CGPointValue];
    valueTemp=pointAarray[2];
    CGPoint endpoint = [valueTemp CGPointValue];
    [path addQuadCurveToPoint:endpoint controlPoint:centerPoint];
    
    CAKeyframeAnimation *animation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    animation.path = path.CGPath;
    animation.duration = 0.6;
    animation.delegate = delegate;
    [imageView.layer addAnimation:animation forKey:nil];
    
    CAKeyframeAnimation *animation1=[CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation1.duration = 0.6;
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1,0.1,0.1)]];
    animation1.values = values;
    [imageView.layer addAnimation:animation1 forKey:nil];
    
    CABasicAnimation *opAnim = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opAnim.duration = 0.6;
    opAnim.fromValue = [NSNumber numberWithFloat:0.1];
    opAnim.toValue= [NSNumber numberWithFloat:1.0];
    [imageView.layer addAnimation:opAnim forKey:nil];
}


//按宽度获取图片合适尺寸
+ (CGSize)newSizeByOriginalSize:(CGSize)oldSize maxSize:(CGSize)mSize newWidth:(float)newWidth
{
    if (oldSize.width <= 0 || oldSize.height <= 0)
    {
        return CGSizeZero;
    }
    CGSize newSize = CGSizeZero;
    if (oldSize.width > mSize.width || oldSize.height > mSize.height)
    {
        //按比例计算尺寸
        float bs = newWidth / oldSize.width;;
        float newHeight = oldSize.height * bs;
        newSize = CGSizeMake(mSize.width, newHeight);
    }
    else
    {
        newSize = oldSize;
    }
    return newSize;
}

//获取字符窜大小
+(CGSize)sizeWithString:(NSString*) string  font:(UIFont*)font size:(CGSize)size
{
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:2];
    NSDictionary *attribute = @{NSFontAttributeName: font, NSParagraphStyleAttributeName:paragraphStyle};
    CGSize textSize = [string boundingRectWithSize:size
                                           options:\
                       NSStringDrawingTruncatesLastVisibleLine |
                       NSStringDrawingUsesLineFragmentOrigin |
                       NSStringDrawingUsesFontLeading
                                        attributes:attribute
                                           context:nil].size;
    return textSize;
}

//获取字符窜大小
+(CGSize)sizeWithString:(NSString*) string  attribute:(NSDictionary*)attribute size:(CGSize)size
{
    CGSize textSize = [string boundingRectWithSize:size
                                           options:\
                       NSStringDrawingTruncatesLastVisibleLine |
                       NSStringDrawingUsesLineFragmentOrigin |
                       NSStringDrawingUsesFontLeading
                                        attributes:attribute
                                           context:nil].size;
    return textSize;
}

//获取NSAttributed字符窜大小
+(CGSize)sizeWithString:(NSAttributedString*) attrStr size:(CGSize)size
{
    CGSize textSize = [attrStr boundingRectWithSize:size
                                            options:\
                       NSStringDrawingTruncatesLastVisibleLine |
                       NSStringDrawingUsesLineFragmentOrigin |
                       NSStringDrawingUsesFontLeading
                                            context:nil].size;
    return textSize;
}


+(float)heightForTextViewSize:(CGSize)size  WithText: (NSString *) strText font:(UIFont*)font
{
    float fPadding = 16.0;
    CGSize constraint = CGSizeMake(size.width - fPadding, CGFLOAT_MAX);
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:5];
    
    NSDictionary *attribute = @{NSFontAttributeName: font, NSParagraphStyleAttributeName:paragraphStyle};
    CGSize newSize = [strText boundingRectWithSize:constraint
                                           options:\
                       NSStringDrawingTruncatesLastVisibleLine |
                       NSStringDrawingUsesLineFragmentOrigin |
                       NSStringDrawingUsesFontLeading
                                        attributes:attribute
                                           context:nil].size;

    newSize.height+=16.0;
    return newSize.height;
}

+(float)heightForTextViewSize:(CGSize)size  WithText: (NSString *) strText attribute:(NSDictionary*)attribute
{
    float fPadding = 16.0;
    CGSize constraint = CGSizeMake(size.width - fPadding, CGFLOAT_MAX);
    CGSize newSize = [strText boundingRectWithSize:constraint
                                           options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin |
                      NSStringDrawingUsesFontLeading
                                        attributes:attribute
                                           context:nil].size;
    
    newSize.height+=16.0;
    return newSize.height;
}

+(float)heightForTextViewSize:(CGSize)size  withAttributeText: (NSAttributedString *) attributeStrText
{
    float fPadding = 16.0;
    CGSize constraint = CGSizeMake(size.width - fPadding, CGFLOAT_MAX);
    CGSize newSize = [attributeStrText boundingRectWithSize:constraint
                                           options:\
                      NSStringDrawingTruncatesLastVisibleLine |
                      NSStringDrawingUsesLineFragmentOrigin |
                      NSStringDrawingUsesFontLeading
                                           context:nil].size;
    
    newSize.height+=16.0;
    return newSize.height;
}

+(UIButton*)buttonWithTitle:(NSString*)title frame:(CGRect)rect
{
    UIButton* button=[UIButton buttonWithType:UIButtonTypeSystem];
    [button setTitle:title forState:UIControlStateNormal];
     button.frame=rect;
    [button.titleLabel setFont:[UIFont fontWithName:@"STHeitiSC-Light" size:15]];
    return button;
}

//MD5加密
+(NSString *)MD5:(NSString *)str{
    //32位MD5小写
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (int)strlen(cStr), result );
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+(int)calculateDaysFromDate:(NSDate*)date
{
    NSString* str=[HDUtil formatter:@"yyyy-MM-dd" FromeDate:date];
    str=[str stringByAppendingString:@" 0:0:0"];
    date=[HDUtil getDateFromeString:str];
    
    NSString* toDateStr=[HDUtil formatter:@"yyyy-MM-dd" FromeDate:[NSDate date]];
    toDateStr=[toDateStr stringByAppendingString:@" 0:0:0"];
    NSDate* toDate=[HDUtil getDateFromeString:toDateStr];
    
    /*
     NSUInteger unitFlags =NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit;
     NSCalendar *cal = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [cal components:unitFlags fromDate:date toDate:today options:0];
    NSInteger days=[comps day];
    NSInteger years=[comps year];
    NSInteger months=[comps month];
    days=(days+months*30+years*365);
     */
    NSTimeInterval time=[toDate timeIntervalSinceDate:date];
    int days=((int)time)/(3600*24);
    return (int)days;
}

+(int)calculateDaysFromDate:(NSDate*)fromDate toDate:(NSDate *)toDate
{
    NSString* fromDateStr=[HDUtil formatter:@"yyyy-MM-dd" FromeDate:fromDate];
    fromDateStr=[fromDateStr stringByAppendingString:@" 0:0:0"];
    fromDate=[HDUtil getDateFromeString:fromDateStr];
    
    NSString* toDateStr=[HDUtil formatter:@"yyyy-MM-dd" FromeDate:toDate];
    toDateStr=[toDateStr stringByAppendingString:@" 0:0:0"];
    toDate=[HDUtil getDateFromeString:toDateStr];
    /*
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSCalendar *cal = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *comps = [cal components:unitFlags fromDate:fromDate toDate:toDate options:0];
    NSInteger days=[comps day];
    NSInteger months=[comps month];
    NSInteger years=[comps year];
    days=(days+months*30+years*365);
    */
    NSTimeInterval time=[toDate timeIntervalSinceDate:fromDate];
    int days=((int)time)/(3600*24);
    return (int)days;
}

+(NSDate*)getDateFromeString:(NSString*)str
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date=[dateFormatter dateFromString:str];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    date = [date  dateByAddingTimeInterval: interval];
    
    if(date==nil)
        date=[NSDate date];
    return date;
}

+(NSString*)formatter:(NSString*) formattter FromeDate:(NSDate*)date
{
    NSString *returnValue;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [dateFormatter setDateFormat:formattter];
    returnValue = [dateFormatter stringFromDate:date];
    return returnValue;
}

+(NSString*)formatter:(NSString*) formattter FromeDateStr:(NSString*)str
{
    NSString *returnValue=[NSString string];
    if(![str isKindOfClass:[NSString class]])
    {
        return returnValue;
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date=[dateFormatter dateFromString:str];
    if(date==nil)
    {
        return returnValue;
    }
    [dateFormatter setDateFormat:formattter];
    returnValue = [dateFormatter stringFromDate:date];
    return returnValue;
}

+ (NSInteger)getTimeSpwithTimestr:(NSString*)timeStr{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    
    NSDate* date = [formatter dateFromString:timeStr];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    return [timeSp integerValue];
}

#pragma mark - 时间搓转为时间字符串
+ (NSString*)getTimeStrFormatter:(NSString*)formattter withTimeSp:(NSInteger)currentInteger{
    NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:currentInteger];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    [dateFormatter setDateFormat:formattter];
    NSString *currentDateStr = [dateFormatter stringFromDate:detailDate];
    return currentDateStr;
}
//是否是今年
+ (BOOL)isCurrentYear:(NSString *)timeStr{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY"];
    NSDate *changeDate = [HDUtil getDateFromeString:timeStr];
    NSString *changeDateString = [dateFormatter stringFromDate:changeDate];
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    if ([changeDateString isEqualToString:currentDateString]) {
        return YES;
    }
    return NO;
}

+ (BOOL)isToday:(NSString *)timeStr{
    NSDate *currentDate = [NSDate date];//获取当前时间，日期
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY/MM/dd"];
    NSDate *changeDate = [HDUtil getDateFromeString:timeStr];
    NSString *changeDateString = [dateFormatter stringFromDate:changeDate];
    NSString *currentDateString = [dateFormatter stringFromDate:currentDate];
    if ([changeDateString isEqualToString:currentDateString]) {
        return YES;
    }
    return NO;
}

+(void)hidenKeyBoard
{
    [[[UIApplication sharedApplication]keyWindow] endEditing:YES];
}

+(NSString*)check:(NSObject*)data
{
    NSString* string=@"";
    if ([data isKindOfClass:[NSString class]])
    {
        string=(NSString*)data;
    }
    else if ([data isKindOfClass:[NSNumber class]])
    {
        double dataNumber=[((NSNumber*)data) doubleValue];
        string=[HDUtil stringDisposeWithDouble:dataNumber];
    }
    return string;
}

+(NSString*)check:(NSObject*)data withDefaultStr:(NSString *)defaultStr
{
    
    NSString* string=defaultStr;
    if ([data isKindOfClass:[NSString class]])
    {
        NSString *dataStr = (NSString*)data;
        if (dataStr.length) {
            string=(NSString*)data;
        }
    }
    else if ([data isKindOfClass:[NSNumber class]])
    {
        float dataNumber=[((NSNumber*)data) floatValue];
        string=[HDUtil stringDisposeWithDouble:dataNumber];
    }
    return string;
}

//浮点数处理并去掉多余的0
+(NSString *)stringDisposeWithDouble:(double)doubleValue
{
    NSString *str = [NSString stringWithFormat:@"%.4f",doubleValue];
    int len = (int)str.length;
    for (int i = 0; i < len; i++)
    {
        if (![str  hasSuffix:@"0"])
            break;
        else
            str = [str substringToIndex:[str length]-1];
    }
    if ([str hasSuffix:@"."])//避免像2.0000这样的被解析成2.
    {
        return [str substringToIndex:[str length]-1];//s.substring(0, len - i - 1);
    }
    else
    {
        return str;
    }
}

//只保留位数，不进行四舍五入
+(NSString *)notRounding:(NSString*)price afterPoint:(int)position{
    if (!price.length) {
        return @"";
    }
    NSArray *tempArray = [price componentsSeparatedByString:@"."];
    if (tempArray.count>1) {//  大于1表示有小数点
        NSString *positionNum = tempArray[1];//取出小数点后边的数
        if ([positionNum integerValue] == 0 || position == 0) {//小数点后为0，或者保留0位小数
            NSRange range = [price rangeOfString:@"."];
            price = [price substringToIndex:range.location];
            return price;
        }
        NSInteger destNum = MIN(positionNum.length, position);
        NSRange range = [price rangeOfString:@"."];
        price = [price substringToIndex:range.location+1+destNum];
    }
    return price;
}

+(NSData*)checkData:(NSData*)value
{
    NSData* data=[NSData data];
    if([value isKindOfClass:[NSData class]])
    {
        data=(NSData*)value;
    }
    return data;
}

+(NSNumber*)checkNumber:(NSNumber*)num
{
    NSNumber* number=[NSNumber numberWithInt:0];
    if([num isKindOfClass:[NSNumber class]])
    {
        number=(NSNumber*)num;
        float dataNumber=[((NSNumber*)number) floatValue];
        NSString* string=[HDUtil stringDisposeWithDouble:dataNumber];
        number=[NSNumber numberWithDouble:[string doubleValue]];
    }
    return number;
}

+(NSArray*)checkNilArray:(NSArray*)array
{
    NSMutableArray* destArray=[[NSMutableArray alloc] initWithCapacity:0];
    if (array!=nil&&([array isKindOfClass:[NSArray class]]||[array isKindOfClass:[NSMutableArray class]]))
    {
        return array;
    }
    
    return destArray;
}

+(NSArray*)checkArray:(NSArray*)array
{
    NSMutableArray* destArray=[[NSMutableArray alloc] initWithCapacity:0];
    if ([array isKindOfClass:[NSArray class]]) {
        return  array;
    }
//    for (NSString* item in array)
//    {
//        NSString* str=[HDUtil clearSpaces:item];
//        if(str.length)
//        {
//            [destArray addObject:str];
//        }
//    }
    return destArray;
}

+(NSString *)currentVersion
{
     return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

+(NSString*)clearSpaces:(NSString*)str
{
    str=[str stringByReplacingOccurrencesOfString:@" " withString:@""];
    return str;
}

+(NSString*)strNumberRound:(NSObject*)data
{
    if ([data isKindOfClass:[NSString class]])
    {
        return [NSString stringWithFormat:@"%d",(int)round([((NSString*)data) doubleValue])];
    }
    else if ([data isKindOfClass:[NSNumber class]])
    {
        return [NSString stringWithFormat:@"%d",(int)round([((NSNumber*)data) doubleValue])];
    }
    return @"-";
}

+ (NSString *)checkPrice:(NSObject*)data
{
    NSString *priceStr = [HDUtil strNumberRound:data];
    if ([priceStr isEqualToString:@"-"]||[priceStr integerValue]<=10) {
        priceStr = @"尚未定价";
    } else {
        priceStr = [NSString stringWithFormat:@"%@万",priceStr];
    }
    return priceStr;
}

+(NSString*)numberFormatterDecimalStyle:(NSNumber*)data
{
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    return [formatter stringFromNumber: data];
}

+(BOOL)call:(NSString *)phoneNumber
{
    NSLog(@"%@",phoneNumber);
    phoneNumber=[HDUtil clearSpaces:phoneNumber];
    return [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phoneNumber]]];
}

+(void)sendPhone:(NSString *)phoneNumber message:(NSString *)message vctr:(UIViewController*)Vctr
{
    NSLog(@"%@",phoneNumber);
    NSArray* phones=[phoneNumber componentsSeparatedByString:@" "];
    phones=[HDUtil checkArray:phones];
    if( [MFMessageComposeViewController canSendText] )
    {
        MFMessageComposeViewController * messageController = [[MFMessageComposeViewController alloc]init];
        messageController.recipients = phones;
        messageController.body = message;
        messageController.messageComposeDelegate = (id)Vctr;
        [Vctr presentViewController:messageController animated:YES completion:nil];
        [[[[messageController viewControllers] lastObject] navigationItem] setTitle:@"新信息"];//修改短信界面标题
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"设备没有短信功能" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];;
    }
}

+(void)showTipAlertWithMsg:(NSString*)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    [self performBlock:^
     {
         [alert dismissWithClickedButtonIndex:0 animated:YES];
     }
    afterDelay:1.2];
}

+ (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

//截屏
+ (UIImage *)screenShot:(UIView *)view
{
    CGRect rect = view.bounds;
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [view.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

//浮窗提示
+(void)showMessage:(NSString *)message
{
    UIWindow * window = [[UIApplication sharedApplication].delegate window];
    UIView *showview =  [[UIView alloc]init];
    
    showview.backgroundColor = [UIColor blackColor];
    showview.frame = CGRectMake(0, 0, KShowMessageDefaultWidth, 60*SCREEN_WIDTH/320);
    showview.center=window.center;
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    label.frame = CGRectMake(5, 0, showview.width-10, showview.height);
    label.numberOfLines=0;
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = YES;
    label.backgroundColor = [UIColor clearColor];
    label.font = HeitiFont(15);
    [showview addSubview:label];
    
    [UIView animateWithDuration:2.5 animations:^{
        showview.alpha = 0.0f;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
    
}

+(CGImageRef)CopyImageAndAlphaChannel:(CGImageRef)sourceImage
{
    CGImageRef retVal=NULL;
    size_t width=CGImageGetWidth(sourceImage);
    size_t height=CGImageGetHeight(sourceImage);
    CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
    CGContextRef offscreenContext=CGBitmapContextCreate(NULL, width, height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
    if (offscreenContext!=NULL)
    {
        CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), sourceImage);
        retVal=CGBitmapContextCreateImage(offscreenContext);
        CGContextRelease(offscreenContext);
    }
    CGColorSpaceRelease(colorSpace);
    return retVal;
}

+(UIImage*)maskImage:(UIImage*)image withMask:(UIImage*)maskImage
{
    CGImageRef maskRef=maskImage.CGImage;
    CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
                                        CGImageGetHeight(maskRef),
                                        CGImageGetBitsPerComponent(maskRef),
                                        CGImageGetBitsPerPixel(maskRef),
                                        CGImageGetBytesPerRow(maskRef),
                                        CGImageGetDataProvider(maskRef), NULL, false);
    
    CGImageRef sourceImage=[image CGImage];
    CGImageRef imageWithAlpha=sourceImage;
    if (CGImageGetAlphaInfo(sourceImage)==kCGImageAlphaNone)
    {
        imageWithAlpha=[HDUtil CopyImageAndAlphaChannel:sourceImage];
    }
    
    CGImageRef masked=CGImageCreateWithMask(imageWithAlpha, mask);
    CGImageRelease(mask);
    if (sourceImage!=imageWithAlpha)
    {
        CGImageRelease(imageWithAlpha);
    }
    
    UIImage* retImage=[UIImage imageWithCGImage:masked];
    CGImageRelease(masked);
    return retImage;
}

//弹出登陆界面
+(void)presentLoginViewControllerSuccess:(void (^)())success {
   
}

+ (NSString *)getCurrentDeviceModel
{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G (A1203)";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G (A1241/A1324)";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS (A1303/A1325)";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 (A1332)";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (A1349)";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S (A1387/A1431)";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (A1428)";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (A1429/A1442)";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (A1456/A1532)";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (A1507/A1516/A1526/A1529)";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (A1453/A1533)";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (A1457/A1518/A1528/A1530)";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus (A1522/A1524)";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 (A1549/A1586)";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s (A1700)";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G (A1213)";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G (A1288)";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G (A1318)";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G (A1367)";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G (A1421/A1509)";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G (A1219/A1337)";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2 (A1395)";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2 (A1396)";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2 (A1397)";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2 (A1395+New Chip)";
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G (A1432)";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G (A1454)";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G (A1455)";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3 (A1416)";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3 (A1403)";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3 (A1430)";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4 (A1458)";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4 (A1459)";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4 (A1460)";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air (A1474)";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air (A1475)";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air (A1476)";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G (A1489)";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G (A1490)";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G (A1491)";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    return platform;
}

+ (UIViewController *)getViewControllerFromView:(UIView *)view
{
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}

+ (NSString *)getJson:(id)theData
{
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    
    if ([jsonData length] > 0 && error == nil){
        NSString *jsonStr = [[NSString alloc] initWithData:jsonData
                                                  encoding:NSUTF8StringEncoding];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        jsonStr = [jsonStr stringByReplacingOccurrencesOfString:@" " withString:@""];
        return jsonStr;
    }else{
        return @"";
    }
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dict;
}

+ (NSString *)URLEncodedString:(NSString *)string
{
    NSString *encodedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)string,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}

+ (NSString *)URLDecodedString:(NSString *)string
{
    NSString *decodedString=(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)string, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    
    return decodedString;
}

#pragma mark 判断url是否加码 NO未加码 YES已加码
+(BOOL)isUrlEncode:(NSString *)string
{
    //未加码url正则
    NSString *urlRegex = @"(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]";
    NSPredicate *urlPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",urlRegex];
    return ![urlPredicate evaluateWithObject:string];
}


+(void)cleanWebViewCache{
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}

@end
























